package com.sy.simpleegg.util

import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat

object BigDecimalUtil {

    private val df = DecimalFormat("#.0")
    private val df2 = DecimalFormat("#.00")
    private val df3 = DecimalFormat("#")

    fun getPrice(price: String?): String? {
        var result = division(price, "100")
        if (result.startsWith(".")) {
            result = "0$result"
        }
        if (result.endsWith("00")){
            result = "0"
        }
        if (result.endsWith(".0")){
            result = result.substring(0, result.length - 2)
        }
        return result
    }

    fun addition(dataStr1: String?, dataStr2: String?): String? {
        val bd1 = BigDecimal(dataStr1)
        val bd2 = BigDecimal(dataStr2)
        val result = bd1.add(bd2)
        return df.format(result)
    }

    fun subtraction(dataStr1: String?, dataStr2: String?): String? {
        val bd1 = BigDecimal(dataStr1)
        val bd2 = BigDecimal(dataStr2)
        val result = bd1.subtract(bd2)
        return df.format(result)
    }

    fun multiplication(dataStr1: String?, dataStr2: String?): String? {
        val bd1 = BigDecimal(dataStr1)
        val bd2 = BigDecimal(dataStr2)
        val result = bd1.multiply(bd2)
        return df.format(result)
    }

    fun division(dataStr1: String?, dataStr2: String?): String {
        if (dataStr1.isNullOrEmpty()){
            return "0"
        }
        val bd1 = BigDecimal(dataStr1)
        val bd2 = BigDecimal(dataStr2)
        val result = bd1.divide(bd2)
//        return df.format(result)
        return if (dataStr1.length > 2 && dataStr1.substring(dataStr1.length - 2) == "00"){
            df.format(result)
        }else if (dataStr1.length > 2 && dataStr1.substring(dataStr1.length - 2) == "00"){
            df.format(result)
        }else{
            df2.format(result)
        }
    }

    fun double2Fen(double: Double): String{
        return df3.format(double*100)
    }

    fun scientificToPlainString(scientificStr: String): String {
        val decimal = BigDecimal(scientificStr)
        // 设置小数点后保留的位数，这里设置为0，表示不舍入
        return decimal.setScale(0, RoundingMode.DOWN).stripTrailingZeros().toPlainString()
    }
}